package com.hsyt.pfc.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

/**
 * @Description: 读取key=value配置文件工具类
 * @ClassName: ResourceUtil
 * @Package: com.yuntai.med.support.core
 * @Author: wangze@hsyuntai.com
 * @Date: 2018年8月8日 13:14
 */
public class ResourceUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtil.class);


    public ResourceUtil() {
    }

    public static Resource[] getResource(String path) {
        try {
            Resource[] locations = (new PathMatchingResourcePatternResolver()).getResources(path);
            return locations;
        } catch (IOException e) {
            throw new RuntimeException("加载code配置文件失败", e);
        }
    }

    public static Resource[] getResource(List<String> configKeys) {
        Resource[] locations = null;

        try {
            locations = new Resource[configKeys.size()];

            for (int i = 0; i < configKeys.size(); ++i) {
                String configKey = (String) configKeys.get(i);
                if (configKey.endsWith("#")) {
                    configKey = configKey.substring(0, configKey.length() - 1);
                }

                locations[i] = (new PathMatchingResourcePatternResolver()).getResource(configKey);
            }


            return locations;
        } catch (Exception e) {
            throw new RuntimeException("加载code配置文件失败", e);
        }
    }

    public static Properties transToProperties(Resource res) {
        InputStream is = null;
        InputStreamReader isr = null;
        Properties prop = null;

        try {
            is = res.getInputStream();
            isr = new InputStreamReader(is);
            prop = new Properties();
            prop.load(isr);
        } catch (Exception e) {
            throw new RuntimeException(String.format("加载%s失败!", res.getFilename()), e);
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    LOGGER.error("", e);
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("", e);
                }
            }

        }

        return prop;
    }
}
